from django import template
register = template.Library()

from django.utils.html import format_html


#自定义标签 解决缩进问题
@register.simple_tag
def sj(res):
    num = res.count(',')-1
    res = num * '|----|'
    return format_html(res)

#自定义 分页标签
@register.simple_tag
def showpages(count,request):
    '''
    count   总页数     100
    p       当前页码    1

    begin   开始页
    end     结束页

    return 10个页码数
    '''

    p = int(request.GET.get('p',1))


    begin = p-4
    end = p+5
    #判断如果当前P小于5
    if p < 5:
        begin = 1
        end = 10
    #判断当前页 如果大于总页数-5
    if p >(count-5):
        begin=count-9
        end = count

    #如果总页数小于10
    if count<10:
        begin=1
        end=count


    #获取页面上的其他搜索条件
    data = request.GET.dict()
    # print(data)
    data.pop('p',None)
    res = ''
    for k,v in data.items():
        res += '&'+k+'='+v


    ps = ""
    if p > 1:
        ps += '<li><a href="?p='+str(p-1)+res+'">«</a></li>'

    for x in range(begin,end+1):
        if p == x:
            ps += '<li class ="am-active"><a href="?p='+str(x)+res+'">'+str(x)+'</a></li>'

        else:
            ps += '<li><a href="?p='+str(x)+res+'">'+str(x)+'</a></li>'

    if p < count:
        ps += '<li><a href="?p='+str(p+1)+res+'">»</a></li>'

    return format_html(ps)

    